package com.googlecode.yoohoo.xmppcore.protocol.parsing;

import java.util.List;

import javax.xml.stream.XMLStreamReader;

import com.googlecode.yoohoo.xmppcore.protocol.XmppProtocolException;
import com.googlecode.yoohoo.xmppcore.protocol.stanza.error.BadRequest;

public class ParsingUtils {
	
	public static String readXmlLang(List<Attribute> attributes) {
		if (attributes.size() == 0)
			return null;
		
		if (attributes.size() != 1)
			throw new XmppProtocolException(new BadRequest("Only allow one attribute 'xml:lang' here"));
		
		String xmlLang = null;
		for (Attribute attribute : attributes) {
			if (!"xml".equals(attribute.getPrefix()) || !"lang".equals(attribute.getLocalName())) {
				throw new XmppProtocolException(new BadRequest(String.format("Invalid attribute '%s:%s'",
						attribute.getPrefix(), attribute.getLocalName())));
			} else {
				xmlLang = attribute.getValue();
			}
		}
		
		return xmlLang;
	}

	public static StringBuilder appendText(XMLStreamReader reader, StringBuilder text) {
		String textFragment = reader.getText().trim();
		// if the characters are white space, ignore them
		if ("".equals(textFragment)) {
			return text;
		}
		
		if (text == null) {
			text = new StringBuilder();
		}
		
		text.append(textFragment);
		return text;
	}
	
}
